﻿namespace GoodAdmin.System;

public class ExtraOrgService : IExtraOrgService, ITransient
{
    private readonly IBaseService _baseService;
    private readonly ISysOrgService _sysOrgService;

    public ExtraOrgService(IBaseService baseService, ISysOrgService sysOrgService)
    {
        _baseService = baseService;
        _sysOrgService = sysOrgService;
    }
    /// <inheritdoc />
    public async Task AddOrg(OrgAddInput input)
    {
        await CheckDataScope(input.ParentId);
        await _sysOrgService.AddOrg(input);
    }
    /// <inheritdoc />
    public async Task DeleteOrg(BaseIdInput input)
    {
        await CheckDataScope(input.Id);
        await _sysOrgService.DeleteOrg(input);
    }
    /// <inheritdoc />
    public async Task<SqlSugarPagedList<SysOrg>> GetOrgPageList(OrgPageInput input)
    {
        if (!UserManager.SuperAdmin)
        {
            var dataScope = await _baseService.GetUserDataScopeByRequest();
            input.DataScope = dataScope;
        }
        return await _sysOrgService.GetOrgPageList(input);
    }
    /// <inheritdoc />
    public async Task<List<SysOrg>> GetOrgTree()
    {
        List<long> dataScope = null;
        if (!UserManager.SuperAdmin)
        {
            dataScope = await _baseService.GetUserDataScopeByRequest();
        }
        return await _sysOrgService.GetOrgTree(dataScope);
    }
    /// <inheritdoc />
    public async Task UpdateOrg(OrgUpdateInput input)
    {
        //当前组织信息（更新前）
        var sysOrg = await _sysOrgService.GetOrgDetail(input.Id);
        var checkOrgIds= new List<long> { input.Id };
        //如果改变了上级组织，那么也需要验证是否有上级组织权限
        if (sysOrg.ParentId != input.ParentId)
        {
            checkOrgIds.Add(input.ParentId);
        }        
        await _baseService.CheckDataScope(checkOrgIds);
        await _sysOrgService.UpdateOrg(input);
    }

    /// <summary>
    /// 检查数据范围
    /// </summary>
    /// <param name="OrgId"></param>
    /// <returns></returns>
    private async Task CheckDataScope(long OrgId)
    {
        await _baseService.CheckDataScope(OrgId);
    }
}